/*
 * SecurityAccess.java
 *
 * Copyright 2012 the original author or authors(ninglong).
 *
 * Licensed under the web-geek, Version 1.0 (the "License");
 *
 */
package org.geek.login.service.impl;

import java.util.Collection;
import java.util.Iterator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;

@Service
public class SecurityAccess implements AccessDecisionManager {
	private static final Logger logger = LoggerFactory.getLogger(SecurityAccess.class);
	
	public void decide(Authentication authentication, Object object,
			Collection<ConfigAttribute> configAttributes)
			throws AccessDeniedException, InsufficientAuthenticationException {
		if (logger.isDebugEnabled()) {  
            logger.debug("decide(Authentication, Object, Collection<ConfigAttribute>) - start");  
        }  
        if (configAttributes == null) {  
            if (logger.isDebugEnabled()) {  
                logger.debug("decide(Authentication, Object, Collection<ConfigAttribute>) - end"); 
            }  
            return;  
        }  
        if (logger.isDebugEnabled()){  
            logger.debug("正在访问的url是："+object.toString());  
        }  
        Iterator<ConfigAttribute> ite = configAttributes.iterator();  
        while (ite.hasNext()) {  
            ConfigAttribute ca = ite.next();  
            logger.debug("needRole is"+ca.getAttribute());  
            String needRole = ((SecurityConfig) ca).getAttribute();  
            for (GrantedAuthority ga : authentication.getAuthorities()) {  
                logger.debug("授权信息"+ga.getAuthority());  
                if (needRole.equals(ga.getAuthority())) { // ga is user's role.  
                    if (logger.isDebugEnabled()) {  
                        logger.debug("判断到，needRole 是"+needRole+",用户的角色是:"+ga.getAuthority()+"授权数据相匹配");  
                        logger.debug("decide(Authentication, Object, Collection<ConfigAttribute>) - end");   
                    }  
                    return;  
                }  
            }  
        }  
        throw new AccessDeniedException("没有权限");  
	}

	public boolean supports(ConfigAttribute arg0) {
		return true;
	}

	public boolean supports(Class<?> arg0) {
		return true;
	}

}
